package crazyboyfeng.autodroid.service;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import crazyboyfeng.autodroid.R;
import crazyboyfeng.autodroid.action.TaskTypeAction;
import crazyboyfeng.autodroid.bean.TaskBean;
import crazyboyfeng.autodroid.db.DBManager;
import crazyboyfeng.autodroid.tasks.TaskManager;
import crazyboyfeng.autodroid.ui.MainActivity;
import crazyboyfeng.autodroid.utils.GlobalContext;


public class AlarmReceiver extends BroadcastReceiver{

	NotificationManager mNM;
	TaskTypeAction action = new TaskTypeAction();
	TaskManager tm = new TaskManager();
	@Override
	public void onReceive(Context context, Intent intent) {
		String id=intent.getExtras().getString("taskId");
		TaskBean task = DBManager.getInstance().getTask(id);
		if(tm.checkTaskTime(task)){
			//是否显示通知
			if(GlobalContext.getInstance().checkNotificationSetting()){
				showNotification(task,context);
			}
		    try{
				action.doTaskType(task);
			}catch (Exception e){
				Log.w("Error", e.getMessage());
			}
		}
	}
	
	private void showNotification(TaskBean task,Context context){
		
		mNM = (NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
    	Intent main = new Intent(context, MainActivity.class);   
    	PendingIntent pIntent = PendingIntent.getActivity(context, 0, main, 0); 
    	
    	String msg = task.getName()+" 已于 "+task.getTime()+" 执行";
    	String str="开启";
    	if(task.getState().equals("N")) str="关闭";
    	String msg2 = task.getTask()+str;
    	
    	NotificationCompat.Builder noti = new NotificationCompat.Builder(context)
         .setContentTitle("自动任务执行通知")
         .setContentText(msg)
         .setSmallIcon(R.drawable.ic_launcher)
         .setContentIntent(pIntent)
         .setAutoCancel(true)
         .setWhen(System.currentTimeMillis())
    	 .setContentInfo(msg2);
    	
    	mNM.notify(Integer.parseInt(task.getId()), noti.build());
	}
	
}
